const crypto = require("crypto");
const {AliPayConfig} = require("../config/AuthConfig");

const {generateToken} = require('./JWT');
const {currentConfig} = require('../config/envConfig');
const sign = (params) => {
    const ordered = {}
    Object.keys(params).sort().forEach(key => {
        if (key !== 'sign' && params[key] !== undefined && params[key] !== '') {
            ordered[key] = params[key]
        }
    })

    const signStr = Object.keys(ordered)
        .map(key => `${key}=${ordered[key]}`)
        .join('&')

    const signer = crypto.createSign('RSA-SHA256')
    signer.update(signStr, 'utf8')  // 指明 utf8 编码
    return signer.sign(AliPayConfig.privateKey, 'base64')
}

// 获取东八区时间，格式为 yyyy-MM-dd HH:mm:ss
function getBeijingTime() {
    const date = new Date(Date.now() + 8 * 60 * 60 * 1000) // 加8小时
    return date.toISOString().slice(0, 19).replace('T', ' ')
}

function handleOAuthRedirect({id, loginName, email = '', avatar = '', name = ''}, loginDevice, res) {
    const user = {
        id,
        loginName,
    };
    const jwtToken = generateToken(user, loginDevice);
    const info = {email, avatar, name};
    console.log( `${currentConfig.frontendUrl}/login`)

    const redirectUrl = `${currentConfig.frontendUrl}/login` +
        `?token=${encodeURIComponent(jwtToken)}` +
        `&email=${encodeURIComponent(info.email)}` +
        `&avatar=${encodeURIComponent(info.avatar)}` +
        `&name=${encodeURIComponent(info.name)}`;
    console.log("redirectUrl", redirectUrl);
    return res.redirect(redirectUrl);
}

function generateLoginResponse({id, loginName, email = '', avatar = '', name = ''}, loginDevice) {
    const user = {id, loginName};
    const jwtToken = generateToken(user, loginDevice);
    const info = {email, picture: avatar, name};
    return {info, jwtToken};
}

module.exports = {
    sign,
    getBeijingTime,
    handleOAuthRedirect,
    generateLoginResponse
}